package com.oocl.crm.service.impl;

import com.oocl.crm.command.Command;
import com.oocl.crm.command.impl.UpdateCommand;
import com.oocl.crm.exception.ParameterErrorException;
import com.oocl.crm.pojo.User;
import com.oocl.crm.service.BusinessService;

/**
 * 更新 指令业务处理
 * @author GANAB
 *
 */
public class UpdateBusinessService extends BusinessService{

	public String service(Command command) throws ParameterErrorException {
		UpdateCommand updateCommand = (UpdateCommand)command;
		User user = null;
		if(updateCommand.getParams()!=null){
			//调用Command 取ID
			String[] userIdAndFields = updateCommand.getUpdateField();
			Integer userId = Integer.parseInt(userIdAndFields[0]);
			String fieldsStr = userIdAndFields[1];
			//校验格式
			if(fieldsStr.matches(USER_FIELDS_REGEX)){
				//正则已经能排除格式问题，直接取数据
				String[] fields = fieldsStr.split(",");
				if(fields != null && fields.length > 0){
					String[] keyValues = null;
					
					for(String field : fields){
						keyValues = field.split(":");
						if(keyValues!=null && keyValues.length == 2){
							user = this.getUserDB().get(userId).data;
							if(user==null){
								return "Not found this user!";
							}
							if(this.getUserDB().update(user, keyValues[0].trim(), keyValues[1].trim())){
								continue;
							}
						}
					}
					return "Update user success! User data is "+user.toString();
				}
			}
		}
		throw new ParameterErrorException("Update user exception: parameter does not conform to the format! ");
	}
}
